package main

import (
	"fmt"
	"log"

	"jianianhua-server/config"
	"jianianhua-server/models"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func main() {
	fmt.Println("检查数据库结构...")

	// 加载配置
	cfg := config.LoadConfig()

	// 连接数据库
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.DBUsername, cfg.DBPassword, cfg.DBHost, cfg.DBPort, cfg.DBName)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("数据库连接失败:", err)
	}

	// 检查并创建表
	checkAndCreateTable(db, &models.User{})
	checkAndCreateTable(db, &models.Product{})
	checkAndCreateTable(db, &models.AppointmentConfig{})
	checkAndCreateTable(db, &models.Appointment{})
	checkAndCreateTable(db, &models.Banner{})

	fmt.Println("数据库结构检查完成！")
}

func checkAndCreateTable(db *gorm.DB, model interface{}) {
	tableName := db.NamingStrategy.TableName(db.Statement.Schema.Name)
	
	// 检查表是否存在
	if !db.Migrator().HasTable(model) {
		fmt.Printf("创建表: %s\n", tableName)
		err := db.Migrator().CreateTable(model)
		if err != nil {
			log.Printf("创建表 %s 失败: %v", tableName, err)
		}
	} else {
		fmt.Printf("表 %s 已存在\n", tableName)
	}
}
